package com.grm.config;

import com.grm.handler.FileUploadHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Netty服务器配置类
 */
@Configuration
public class NettyServerConfig {

    @Value("${netty.workThread}")
    private Integer workThread;

    @Value("${netty.bossThread}")
    private Integer bossThread;

    @Value("${netty.keepAlive}")
    private Boolean keepAlive;

    /**
     * 创建并配置ServerBootstrap实例
     *
     * @return 配置好的ServerBootstrap实例
     */
    @Bean
    public ServerBootstrap serverBootstrap() {
        // 创建Boss组，用于接收客户端连接请求
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(bossThread);
        // 创建Worker组，用于处理IO操作
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(workThread);
        // 初始化服务器引导类
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // 配置服务器引导类
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class) // 使用NioServerSocketChannel作为服务器的通道实现
                .option(ChannelOption.SO_BACKLOG, 1024) // 服务器的连接队列长度为1024
                .childOption(ChannelOption.SO_KEEPALIVE, keepAlive) // 使用keepAlive配置
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        // 配置通道管道
                        ch.pipeline().addLast(
                                new HttpResponseEncoder(), // HTTP响应编码器
                                new HttpRequestDecoder(), // HTTP请求解码器
                                new ChunkedWriteHandler(), // 支持分块写入
                                new FileUploadHandler() // 自定义的处理器
                        );
                    }
                });
        // 返回配置好的ServerBootstrap实例
        return serverBootstrap;
    }
}
